package com.le.edu.controller;

import com.le.edu.domain.entity.Video;
import com.le.edu.domain.vo.CreateTaskParam;
import com.le.edu.domain.vo.TaskInfoVo;
import com.le.edu.resp.Result;
import com.le.edu.service.VideoService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Le
 * @create 2024-04-09 20:50
 */
@Tag(name = "视频接口")
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/vod")
public class VideoController extends BaseController {
    private final VideoService videoService;


    /**
     * 1.获取上传进度
     * -上传完直接返回 finished
     * -未上传完，返回已上传的分片
     * -未上传，返回 null
     *
     * @param identifier 文件md5
     * @return
     */
    @Operation(summary = "获取上传进度")
    @GetMapping("/{identifier}")
    public Result<TaskInfoVo> taskInfo(@PathVariable("identifier") String identifier) {
        return Result.ok(videoService.getTaskInfo(identifier));
    }

    /**
     * 2.创建上传任务
     *
     * @return
     */
    @Operation(summary = "创建上传任务")
    @PostMapping
    public Result<TaskInfoVo> createTask(@Valid @RequestBody CreateTaskParam param, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return Result.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        return Result.ok(videoService.createTask(param));
    }

    /**
     * 3.获取每个分片的预签名上传地址
     *
     * @param identifier
     * @param partNumber
     * @return
     */
    @Operation(summary = "获取每个分片的预签名上传地址")
    @GetMapping("/{identifier}/{partNumber}")
    public Result<String> preSignUploadUrl(@PathVariable("identifier") String identifier,
                                           @PathVariable("partNumber") Integer partNumber) {
        Video task = videoService.getByIdentifier(identifier);
        if (task == null) {
            return Result.fail("分片任务不存在");
        }
        Map<String, String> params = new HashMap<>(2);
        params.put("partNumber", partNumber.toString());
        params.put("uploadId", task.getUploadId());
        return Result.ok(videoService.genPreSignUploadUrl(task.getBucketName(), task.getObjectKey(), params));
    }

    /**
     * 4.合并分片
     *
     * @param identifier
     * @return
     */
    @Operation(summary = "合并分片")
    @PostMapping("/merge/{identifier}")
    public Result<Void> merge(@PathVariable("identifier") String identifier) {
        videoService.merge(identifier);
        return Result.ok();
    }

    @Operation(summary = "删除视频")
    @PostMapping("/deleteVideo")
    public Result<Void> deleteVideo(@RequestBody Video video) {
        videoService.deleteVideo(video);
        return Result.ok();
    }
}
